﻿namespace Thor.WebRole
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Net;
    using System.Runtime.Serialization;
    using System.Web.DomainServices;
    using System.Web.Ria;
    using System.Web.Ria.ApplicationServices;
    using System.Web.Security;
    using Thor.Domain;
    using Thor.Domain.Configuration;

    /// <summary>
    ///    RIA Services DomainService responsible for authenticating users when
    ///    they try to log on to the application.
    ///    
    ///    Most of the functionality is already provided by the base class
    ///    AuthenticationBase
    /// </summary>
    [EnableClientAccess]
    public class AuthenticationService : DomainService, IAuthentication<User> 
    {
        private static User DefaultUser = new User() { Name = string.Empty };

        public User GetUser()
        {
            if ((this.ServiceContext != null) &&
                (this.ServiceContext.User != null) &&
                this.ServiceContext.User.Identity.IsAuthenticated)
            {
                return this.GetUser(this.ServiceContext.User.Identity.Name);
            }
            return AuthenticationService.DefaultUser;
        }

        private User GetUser(string userName)
        {
            return new User() { Name = userName };
        }

        public bool IsUserAdministrator(string userName)
        {
            string separator = @"\";

            if (userName.Contains(separator))
            {
                string[] userNameSplit = userName.Split(separator.ToCharArray());
                userName = userNameSplit[1];
            }

            return AdministratorAccountHelper.IsAdministrator(userName);
        }

        public User Login(string userName, string password, bool isPersistent, string customData)
        {
            string separator = @"\";
            string originalUserName = userName;
            NetworkCredential credential = null;

            if (userName.Contains(separator))
            {
                string[] userNameSplit = userName.Split(separator.ToCharArray());
                string domain = userNameSplit[0];
                userName = userNameSplit[1];
                credential = new NetworkCredential(userName, password, domain);
            }
            else
                credential = new NetworkCredential(userName, password);

            //if the logon is locked, do not proceed
            if (InvalidLogonHelper.IsLogonLocked(userName))
                return null;

            var settings = SettingsHelper.GetSettings();

            string serviceUrl = settings.CalendarProviderUri;

            var result = CalendarProviderHelper.GetCalendarProvider(settings.AssemblyName, settings.AssemblyType).Authenticate(credential, serviceUrl);

            if (result.Success)
            {
                FormsAuthentication.SetAuthCookie(userName, isPersistent);
                return this.GetUser(userName);
            }
            else
            {
                InvalidLogonHelper.Update(originalUserName);
                return null;
            }
        }

        public User Logout()
        {
            FormsAuthentication.SignOut();
            return AuthenticationService.DefaultUser;
        }

        public void UpdateUser(User user)
        {
            throw new System.NotImplementedException();
        }
    }
}
